package com.sec.android.app.myfiles.feature.Hover;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnHoverListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.facade.cmd.DeleteRecordCmd;
import com.sec.android.app.myfiles.feature.DlpMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.util.DrmUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * Created by daelight.kim on 2017-07-05.
 */

public class PlayableMediaHoverView implements OnHoverListener {

    private final AbsMyFilesFragment mFragment;
    protected FileRecord mRecord = null;
    protected final Context mContext;
    protected Dialog mDialog = null;
    protected Handler mHandler = null;
    private final float mAirViewMaxWidth;
    private final float mAirViewMaxHeight;

    public boolean mIsBtnHovered = false;
    public boolean mIsLayoutHover = false;
    protected boolean mIsStarted = false;

    protected View mView;
    protected LinearLayout mLayout = null;
    private Window mWindow;

    protected MediaPlayer mMediaPlayer = null;
    protected MediaAirViewImageButton mPlayButton = null;

    private Rect mHoverRect;
    protected String mFilePath = null;

    protected static class HoverMsg {
        public static final int MSG_SHOW_POPUP = 0;
        public static final int MSG_SHOW = 1;
        public static final int MSG_DISMISS_POPUP = 2;
    }

    public PlayableMediaHoverView(Activity activity, AbsMyFilesFragment fragment, FileRecord record) {
        mContext = activity.getApplicationContext();
        mFragment = fragment;
        mRecord = record;
        mAirViewMaxWidth = mContext.getResources().getDimension(R.dimen.airview_preview_max_width);
        mAirViewMaxHeight = mContext.getResources().getDimension(R.dimen.airview_preview_max_height);
        mDialog = new Dialog(activity);
        mHandler = new PlayableMediaHoverView.WeakRefHandler(this);

        mContext.setTheme(R.style.MyFiles_Default);
        setDialogProperties();
    }


    private static class WeakRefHandler extends Handler {
        WeakReference<PlayableMediaHoverView> mPlayableMediaHoverView = null;

        WeakRefHandler(PlayableMediaHoverView activity) {
            mPlayableMediaHoverView = new WeakReference<>(activity);
        }

        public void handleMessage(Message msg) {
            PlayableMediaHoverView mediaHoverView = mPlayableMediaHoverView.get();
            if (mediaHoverView == null) {
                return;
            }

            switch (msg.what) {
                case PlayableMediaHoverView.HoverMsg.MSG_SHOW_POPUP: // show
                    mediaHoverView.initViews();
                    mediaHoverView.mHandler.sendEmptyMessage(PlayableMediaHoverView.HoverMsg.MSG_SHOW);
                    break;
                case PlayableMediaHoverView.HoverMsg.MSG_SHOW:
                    if (mediaHoverView.mDialog != null)
                        mediaHoverView.mDialog.show();
                    break;
                case PlayableMediaHoverView.HoverMsg.MSG_DISMISS_POPUP: // dismiss
                    mediaHoverView.dismissPopup();
                    break;
            }
        }
    }

    public void setParam(View v, Rect rect, String path) {
        mView = v;
        mHoverRect = rect;
        mFilePath = path;
    }

    protected void initViews() {
        if (mDialog == null) {
            if (mFragment == null || mFragment.getActivity() == null) {
                return;
            }
            mDialog = new Dialog(mFragment.getActivity());
            setDialogProperties();
        }

    }

    private void setDialogProperties() {
        if (mDialog != null) {
            mWindow = mDialog.getWindow();
            mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            mWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            mWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        }
    }

    protected void setDialogPosition(int leftMargin, int topMargin) {
        if (mWindow != null) {
            WindowManager.LayoutParams params = mWindow.getAttributes();
            params.x = mHoverRect.left + leftMargin;
            params.y = mHoverRect.top - topMargin;
            mWindow.setAttributes(params);
            mWindow.setGravity(Gravity.TOP | Gravity.START);
        }
    }


    protected float getRatio(float width, float height) {
        float ratio;
        if ((mAirViewMaxWidth / width) > (mAirViewMaxHeight / height)) {
            ratio = mAirViewMaxHeight / height;
        } else {
            ratio = mAirViewMaxWidth / width;
        }
        return ratio;
    }

    protected void initHoverButton() {
        mLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    MyFilesFacade.executeRecord(mFragment.getProcessId(), mFragment.getActivity(), mRecord);
                }
                return false;
            }
        });

        View airViewButtonLayout = mLayout.findViewById(R.id.air_button_include_layout);
        mPlayButton = (MediaAirViewImageButton) airViewButtonLayout.findViewById(R.id.air_button_play);
        if (mPlayButton != null) {
            mPlayButton.setBackground(mContext.getDrawable(R.drawable.hover_play_btn));
            mPlayButton.setContentDescription(mContext.getResources().getString(R.string.hover_play));
            mPlayButton.setAirViewManager(this);
            mPlayButton.setOnHoverListener(this);
        }

        MediaAirViewImageButton shareButton = (MediaAirViewImageButton) airViewButtonLayout.findViewById(R.id.air_button_share_via);
        if (shareButton != null) {
            shareButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    MyFilesFacade.shareVia(mFragment.getProcessId(), mContext, mFragment, makeFileRecordList(mRecord), false, false);
                    dismissPopup();
                }
            });
            shareButton.setAirViewManager(this);
            shareButton.setOnHoverListener(this);

            if (DrmUtils.isDRMFile(mContext, mRecord.getFullPath())) {
                shareButton.setVisibility(View.GONE);
            }
        }

        MediaAirViewImageButton deleteButton = (MediaAirViewImageButton) airViewButtonLayout.findViewById(R.id.air_button_delete_via);
        if (deleteButton != null) {
            deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    if (mRecord.getStorageType() == FileRecord.StorageType.Recent
                            || mRecord.getStorageType() == FileRecord.StorageType.Downloads) {
                        MyFilesFacade.deleteRecord(mFragment.getProcessId(), mContext, mFragment, makeFileRecordList(mRecord),
                                DeleteRecordCmd.OperationProgress.DO_OPERATE);
                    } else {
                        MyFilesFacade.deleteRecord(mFragment.getProcessId(), mContext, mFragment, makeFileRecordList(mRecord),
                                DeleteRecordCmd.OperationProgress.SHOW_SINGLE_CONFIRM_POPUP);
                    }
                    dismissPopup();
                }
            });
            deleteButton.setAirViewManager(this);
            deleteButton.setOnHoverListener(this);
        }
    }

    private ArrayList<FileRecord> makeFileRecordList(FileRecord record) {
        ArrayList<FileRecord> ret = new ArrayList<>();
        ret.add(record);
        return ret;
    }

    protected void initOverlayIcons() {
        ImageView dlpIcon = (ImageView) mLayout.findViewById(R.id.dlp_icon);
        if (DlpMgr.getInstance(mContext).isDlpFile(mRecord)) {
            dlpIcon.setVisibility(View.VISIBLE);
        }
    }

    public void dismissPopup() {
        if (mDialog != null && mDialog.isShowing()) {
            if (mMediaPlayer != null) {
                mMediaPlayer.release();
            }
            try {
                mDialog.dismiss();
            } catch (IllegalArgumentException e) {
                Log.e(this, "IllegalArgumentException:" + e.toString());
            }
            mDialog = null;
        } else {
            if (mMediaPlayer != null) {
                mMediaPlayer.release();
            }
        }
    }

    protected OnHoverListener mLayoutListener = new View.OnHoverListener() {
        public boolean onHover(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_HOVER_ENTER:
                    mIsLayoutHover = true;
                    if (mHandler.hasMessages(HoverMsg.MSG_DISMISS_POPUP)) {
                        mHandler.removeMessages(HoverMsg.MSG_DISMISS_POPUP);
                    }
                    break;
                case MotionEvent.ACTION_HOVER_MOVE:
                    if (mHandler.hasMessages(HoverMsg.MSG_DISMISS_POPUP)) {
                        mHandler.removeMessages(HoverMsg.MSG_DISMISS_POPUP);
                    }
                    break;
                case MotionEvent.ACTION_HOVER_EXIT:
                    mIsLayoutHover = false;
                    if (!mIsBtnHovered) {
                        mHandler.sendEmptyMessage(HoverMsg.MSG_DISMISS_POPUP);
                        mHandler.sendEmptyMessage(HoverMsg.MSG_DISMISS_POPUP);
                        removeDelayedMessage();
                    }
                    break;
                default:
                    break;
            }
            return true;
        }
    };

    public void sendDelayedMessage(int ms) {
        if (mHandler.hasMessages(HoverMsg.MSG_SHOW_POPUP)) {
            mHandler.removeMessages(HoverMsg.MSG_SHOW_POPUP);
        }
        mHandler.sendEmptyMessageDelayed(HoverMsg.MSG_SHOW_POPUP, ms);
    }

    public void removeDelayedMessage() {
        if (mHandler.hasMessages(HoverMsg.MSG_SHOW_POPUP)) {
            mHandler.removeMessages(HoverMsg.MSG_SHOW_POPUP);
        }
        mHandler.sendEmptyMessageDelayed(HoverMsg.MSG_DISMISS_POPUP, 10);
    }

    @Override
    public boolean onHover(View v, MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_HOVER_EXIT:
            case MotionEvent.ACTION_HOVER_ENTER:
            case MotionEvent.ACTION_HOVER_MOVE:
                if (mHandler.hasMessages(HoverMsg.MSG_DISMISS_POPUP)) {
                    mHandler.removeMessages(HoverMsg.MSG_DISMISS_POPUP);
                }
                break;
        }
        return false;
    }

    public boolean isBtnHovered() {
        return mIsBtnHovered;
    }

    public void setBtnHovered(boolean isBtnHovered) {
        mIsBtnHovered = isBtnHovered;
    }

    public boolean isLayoutHover() {
        return mIsLayoutHover;
    }
}
